package com.example.demo.common.advice;

import com.example.demo.exception.BlogException;
import com.example.demo.pojo.response.BlogInfoDetailResponse;
import com.example.demo.pojo.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.annotation.HandlerMethodValidationException;

import java.util.ArrayList;
import java.util.List;

@ControllerAdvice
@ResponseBody
@Slf4j
public class ExceptionAdvice {

    @ExceptionHandler
    public Result handle(MethodArgumentNotValidException e){
        log.error("e：{}",e);
        List<ObjectError> allErrors = e.getAllErrors();
        StringBuilder stringBuilder=new StringBuilder();
        for (ObjectError error:allErrors
             ) {
            stringBuilder.append(error.getDefaultMessage());
        }
        return Result.fail(stringBuilder.toString());
    }
    @ExceptionHandler
    public Result handle(HttpMessageNotReadableException e){
        log.error("参数校验不通过：{}",e);
        return Result.fail("参数校验不通过");
    }
    @ExceptionHandler
    public Result handle(Exception e){
        log.error("发生了异常 e:",e);
        return Result.fail("发生了异常");
    }
    @ExceptionHandler
    public Result handle(BlogException blogException){
        log.error("blogException:{}",blogException.getMsg());
        return Result.fail(blogException.getMsg());
    }

    @ExceptionHandler
    public Result parameterValidation(HandlerMethodValidationException e){
        log.info("e:{}",e);
        List<String> errors = new ArrayList<>();
        e.getAllErrors().forEach(error ->
                errors.add(error.getDefaultMessage()));
        StringBuffer msg=new StringBuffer();
                errors.stream().forEach(x->{
            msg.append(x+" ");
        });
        log.info("msg:{}",msg);
        return Result.fail(msg.toString());
    }
}
